function autoCorrect(target, evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode;
	if (charCode == 32 || charCode == 9) {
		$.post (
			"../AutoCorrect/replaceAjax?set_ajax_view", {source: $("#" + target).val()},
			function(data) {
				if (data.replace != "") {
					$("#" + target).val($("#" + target).val().replace(data.source, data.replace));
				}
			}, "json");
	}
}

function showHideElement(elementId) {
	$('#' + elementId).toggle();
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
/**
* Return number of days in February
* @param year
* @return
* 29: leap year
* 28: not a leap year
*/
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function validateDateVN(dtStr,showAlert,minYear,maxYear){
    var min=1900;
    var max=2100;
    var show=true;
    if(showAlert!=null)
    	show=showAlert;
    if(minYear!=null)
        min=minYear;
    if(maxYear!=null)
        max=maxYear;  
    var dtCh= "/" ;
    var regxDateVN = /^(\d{1,2}\/)?(\d{1,2}\/)?\d{4}$/; 
    var daysInMonth = DaysArray(12);
    if(!regxDateVN.test(dtStr)){
        if(show==true)
            alert("Please enter a date matching one of the formats: (dd/mm/yyyy), (mm/yyyy), (yyyy)");
        return 1; // Error code=1: Date not match available date formats    
    }
    var dtParts = dtStr.split(dtCh);
    var parts=new Array(3);
    parts[0]="0";// day
    parts[1]="0";// month
    parts[2]="0";// year
    var j=2;
    for(var i=dtParts.length-1;i>=0;i--){
        parts[j]=dtParts[i];
        j--;
    }
    var day=parseInt(parts[0]);
    var month=parseInt(parts[1]);
    var year=parseInt(parts[2]);
    if (day!=0 && (day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])){
        if(show==true)
            alert("Please enter a valid day");
        return 2;// Error code=2: Day is not valid.
    }
    
    if ((day!=0 && month==0) || (month!=0 && (month<1 || month>12))){
        if(show==true)
            alert("Please enter a valid month");
        return 3;// Error code=4: Month is not valid.
    }
    
    if (year==0 || year<min || year>max){
        if(show=true)
            alert("Please enter a valid 4 digit year between "+min+" and "+max);
        return 4;// Error code=4: Year is not valid.
    }
    
    return 0;// Error code=0: No errors
}

function manipulateDiv(action, divId) {
	if (action == "toggle") {
		$("#" + divId).toggle();
	} else if (action == "show") {
		$("#" + divId).show();
	} else if (action == "hide") {
		$("#" + divId).hide();
	}
}

function switchDiv(divIdCur, divIdNext) {
	$("#" + divIdCur).toggle();
	$("#" + divIdNext).toggle();
}

function number_format( number, decimals, dec_point, thousands_sep ) {
	// http://kevin.vanzonneveld.net
 	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
 	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 	// +     bugfix by: Michael White (http://crestidg.com)
 	// +     bugfix by: Benjamin Lupton
 	// +     bugfix by: Allan Jensen (http://www.winternet.no)
 	// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)   
 	// *     example 1: number_format(1234.5678, 2, '.', '');
 	// *     returns 1: 1234.57     
 	
 	var n = number;
	var c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
 	var d = dec_point == undefined ? "," : dec_point;
 	var t = thousands_sep == undefined ? "." : thousands_sep;
	var s = n < 0 ? "-" : "";
 	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "";
	var j = (j = i.length) > 3 ? j % 3 : 0;
 	   
 	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function convert_number(number) {
	if (isNaN(number)) {
		numbers = new Array();
		numbers = number.split('/');
		number = numbers[0]/numbers[1];
	}
	return number;
}

function printRefraction(recordId, printSign, lang) {
	$.get(
		'../MedicalPrintView/checkRefraction2?set_ajax_view',
		{
		recordId: recordId
		},
		function (data){
			if (data == 'OK'){				
				var url='../MedicalPrintView/ViewRefractionPrintFromRecord?recordId=' + recordId + '&set_print_view&printSign=' + printSign + '&lang=' + lang;
				window.open(url, '', 'scrollbars=yes, menubar=no, height=700, width=800, resizable=yes, toolbar=no, location=no, status=no');				
			} else {
				generalDialog(null,null,_('There is no refaction in this medical record'));				
			}
		}
	);
}

function printPrescription(recordId, printSign, lang) {	
	$.get(
		'../MedicalPrintView/checkPrescription2?set_ajax_view',
		{
		recordId: recordId
		},
		function (data){
			if (data == 'OK'){				
				var url='../MedicalPrintView/ViewPrescriptionPrintFromRecord?recordId=' + recordId + '&set_print_view&printSign=' + printSign + '&lang=' + lang;
				window.open(url, '', 'scrollbars=yes, menubar=no, height=700, width=800, resizable=yes, toolbar=no, location=no, status=no');				
			} else {
				generalDialog(null,null,_('Patient does not have a prescription.'));				
			}
		}
	);	
}

function getRecentPatient(userId) {
	$.ajax ({
		type:     "GET",
		url:	  "../RecentItem/getRecentPatient?set_ajax_view",
		dataType: "json",
		success:  function(data) {
			$('#recentPatientHeader').html(data.header);
			$('#recentPatientBody').html(data.body);
		}
	});
}

function fastSearchPatientCode(searchString, controller, actionName , divIdFillSearchResult, redirect, showError) {
	
	if (searchString != '') {
		$('#quickSearch').val(_("Searching..."));
		$.ajax ({
			type:     "POST",
			url:	  "../PatientFinder/fastSearchPatientCode?set_ajax_view",
			data: 	  "patientCode=" + searchString
					 +"&controller=" + controller
					 +"&actionName=" + actionName
					 +"&redirect=" + redirect
					 +"&insurance=" + $('#insurance').val()
			,			
			dataType: "json",
			success:  function(data) {
				$('#quickSearch').val(searchString);
				if (data.error.code == 'OK') {
					if (redirect == 1) {
						window.location = data.result;
					} else {
						$('div#' + divIdFillSearchResult).html(data.result);						
					}
					
				} else {
										
					var buttons = {};
					buttons[_('Close')] = function() {
						$(this).dialog('close');
						$('#quickSearch').val('').focus();
					};	
					if (showError == true) {
					generalDialog(null, _('Search patient'), _("Cannot find patient: <b>{0}</b>",searchString), 'warn', {
						autoOpen: true,			
						bgiframe: true,
						resizable: false,
						modal: true,
						buttons: buttons,
						dialogClass: 'custom-dialog'
					}, _('Close'));			
					}
				}
				
			}
		});
	}
}
function fastSearchPatient(controller, actionName , divIdFillSearchResult, redirect, showError) {
	var searchString = $.trim($('#quickSearch').val());
	if (searchString == '') {
		return;
	}	
	var numbers = searchString.match(/\d+\.?\d*/g);
	if (numbers == null) {
		fastSearchPatientName(searchString,controller, actionName , divIdFillSearchResult, redirect, showError);
		
	} else {
		fastSearchPatientCode(searchString,controller, actionName , divIdFillSearchResult, redirect, showError);
	}
	
}

function fastSearchPatientNameAfter(patientId, controller, actionName , divIdFillSearchResult, divDialog) {
	
	$.ajax ({
		type:     "POST",
		url:	  "../PatientFinder/fastSearchPatientNameAfter?set_ajax_view",
		data: 	  "patientId=" + patientId
				 +"&controller=" + controller
				 +"&actionName=" + actionName	
				 +"&insurance=" + $('#insurance').val()
		,			
		dataType: "json",
		success:  function(data) {
			if (data.error.code == 'OK') {
				if (divDialog != null && divDialog != '') {
					$('#' + divDialog).dialog('close');
				}
				$('div#' + divIdFillSearchResult).html(data.result);
				
			} else {
									
				var buttons = {};
				buttons[_('Close')] = function() {
					$(this).dialog('close');
					$('#quickSearch').val('').focus();
				};
				if (showError == true) {
				generalDialog(null, _('Search patient'), _("Cannot find patient: <b>{0}</b>",searchString), 'warn', {
					autoOpen: true,			
					bgiframe: true,
					resizable: false,
					modal: true,
					buttons: buttons,
					dialogClass: 'custom-dialog'
				}, _('Close'));		
				}
			}
			
		}
	});
}

function processMultiSearchResult(result, controller, actionName , divIdFillSearchResult, redirect) {
	
	var table = "<table style='width:100%;' cellspacing='0' cellpadding='0' class='grid'>";
	var url ='';
	table += '<thead>';
	table += '<tr>';
	table += '<th style="width: 200px;">' + _('Name') + '</th>';
	table += '<th style="width: 110px;">' + _('Patient code') + '</th>';
	table += '<th style="width: 110px;">' + _('Day of birth') + '</th>';
	table += '<th style="width: 110px;">' + _('Phone') + '</th>';
	table += '<th>' + _('Address') + '</th>';
	table += '</tr>';
	table += '</thead>';	

	for ( var int = 0; int < result.length; int++) {
		table += '<tr>';
		table += '<td>';
		if (redirect ==0) {
			table += '<a href="javascript:fastSearchPatientNameAfter(' + result[int]['person_id'] + ',\'' + controller + '\',\'' + actionName + '\',\'' + divIdFillSearchResult + '\',\'patientSearchDialog1111\')">' + result[int]['name'] + "</a>";
		} else {
			url = "../" + controller + "/" + actionName + "?patientId=" + result[int]['person_id'];
			table += '<a href="' + url + '">' + result[int]['name'] + "</a>";
			
		}
		table += '</td>';
		table += '<td>' + result[int]['patient_code'] + '</td>';
		table += '<td>' + result[int]['date_of_birth'] + '</td>';
		table += '<td>' + result[int]['phone_number'] + '</td>';
		table += '<td>' + result[int]['address'] + '</td>';
		table += '</tr>';
	}
	table += '</table>';
	
	var buttons = {};
	buttons[_('Close')] = function() {
		$(this).dialog('close');
		$('#quickSearch').val('').focus();
	};					
	var dialog = generalDialog("patientSearchDialog1111", _('Search patient'), table, null, {
		autoOpen: true,			
		bgiframe: true,
		resizable: true,				
		width: 850,
		height: 450,
		modal: true,
		buttons: buttons,
		dialogClass: 'custom-dialog'
	}, _('Close'));	
	
}

function fastSearchPatientName(searchString, controller, actionName , divIdFillSearchResult, redirect, showError) {
	
	if (searchString != '') {
		$('#quickSearch').val(_("Searching..."));
		$.ajax ({
			type:     "POST",
			url:	  "../PatientFinder/fastSearchPatientName?set_ajax_view",
			data: 	  "patientName=" + searchString										 
			,			
			dataType: "json",
			success:  function(data) {
				$('#quickSearch').val(searchString);
				if (data.error.code == 'OK') {
					var result = data.result;
					if (result.length ==1) {
						if(redirect == 1) {
							window.location = "../" + controller + "/" + actionName + "?patientId=" + result[0]['person_id'];							
						} else {
							fastSearchPatientNameAfter(result[0]['person_id'], controller, actionName , divIdFillSearchResult, null);							
						}
					
					} else {
						processMultiSearchResult(data.result, controller, actionName , divIdFillSearchResult, redirect);
					
					//2. if multi record->show popup to select
					//2.1 if redirect
					
				    //2.2 not redirect
					}
					
				} else {
										
					var buttons = {};
					buttons[_('Close')] = function() {
						$(this).dialog('close');
						$('#quickSearch').val('').focus();
					};	
					if (showError == true) {
						generalDialog(null, _('Search patient'), _("Cannot find patient: <b>{0}</b>",searchString), 'warn', {
							autoOpen: true,			
							bgiframe: true,
							resizable: false,
							modal: true,
							buttons: buttons,
							dialogClass: 'custom-dialog'
						}, _('Close'));			
					}
				}
				
			}
		});
	}
}

var currentMainNav = "";

function activeMenu(mainNav, subNav) {
	currentMainNav = mainNav;
	$(".mainNav li").removeClass('active');
	$("#main_nav_" + mainNav).addClass('active');
	$("#parent_nav_" + mainNav + " li").removeClass('active');
	$("#sub_nav_" + subNav).addClass('active');
	$("#parent_nav_" + mainNav).show();
}

function showNavTab(mainNav) {
	$(".subNav").hide();
	$("#parent_nav_" + mainNav).show();
}
var LocalizedStrings=[];
/**
 * Localize for given key (text)
 * key in vi_VN/lang.js
 * LocalizedStrings["First name: {0} Last name: {1}"]="Họ {1} Tên: {0}"
 * Ex:
 *  _("First name: {0} Last name: {1}", "Harry", "Potter");
 * result in en_US [First name: Harry Last name: Potter]
 * result in vi_VN [Họ: Potter Tên: Harry]
 * @param key
 * @return
 * content of the key according to selected language
 */
function _(key){ 
	var s;
	if (LocalizedStrings == null 
			|| LocalizedStrings[key] == null) {
		s = key;
	} else {
		s = LocalizedStrings[key];
	}

	//check if there are two arguments in the arguments list
    if ( arguments.length <= 1 )
    {
    	//if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return s;
    }
    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ )
    {
        //iterate through the tokens and replace their placeholders from the original text in order
        s = s.replace( new RegExp( "\\{" + token + "\\}", "gi" ),
                                                arguments[ token + 1 ] );
    }
    return s
}; 
/**
 * Add date timepicker to [idYear] text box 
 * @param idDay : id of text box day
 * @param idMonth: id of text box month
 * @param idYear: id of text box year
 * @param changeMonth: 
 * true: allow use select month from a combobox
 * false: hide the month combobox 
 * @param changeYear
 * true: allow use select year from a combobox
 * false: hide the year combobox  
 * @param initCurrentDay
 * true: will auto fill current date into day,month,year text box at start up
 * false: day, month year text box is empty at start up
 * @return
 */
function addDatePicker(idDay,idMonth,idYear,changeMonth,changeYear,initCurrentDay) {
	
	$(idYear).datepicker({
		dateFormat: 'dd/mm/yy',
		gotoCurrent: true,
		buttonImage: '../images/calendar.gif',
		buttonImageOnly: true,
		showOn: 'button',
		changeMonth: changeMonth,
		changeYear: changeYear,
		onSelect: function(dateText, inst) {                        
	
	        $(idDay).val(inst.selectedDay);
	
	        $(idMonth).val(inst.selectedMonth + 1);
	
	        $(this).val(inst.selectedYear);                        
	
	    }
	});
	if (initCurrentDay == true) {
		var dt=new Date();
		var mo = dt.getMonth() + 1;  
		var day = dt.getDate(); 
		$(idDay).val(day < 10? "0" + day: day);
		$(idMonth).val(mo < 10? "0" + mo: mo);
		$(idYear).val(dt.getFullYear());
	}
	
	var fields = $(idDay).parents('form:eq(0),body').find('input').not('[type=hidden]');
	var indexMon = fields.index( $(idMonth) );
	var indexDay = fields.index( $(idDay) );
	var indexYear = fields.index( $(idYear) );
	
	
	if (indexDay < indexMon) {		
		$(idDay).autotab({ target: $(idMonth).attr('id'), maxlength: 2, format: 'numeric' });
		$(idMonth).autotab({ target: $(idYear).attr('id'), maxlength: 2, format: 'numeric' });
		
	} else {
		
		$(idMonth).autotab({ target: $(idDay).attr('id'), maxlength: 2, format: 'numeric' });
		$(idDay).autotab({ target: $(idYear).attr('id'), maxlength: 2, format: 'numeric' });
				
	}
	
	if ( indexYear > -1 && ( indexYear + 1 ) < fields.length ) {
		$(idYear).autotab({ target: fields.eq( indexYear + 1 ).attr('id'), maxlength: 4, format: 'numeric' });
        
    }
	
	
}

/**
* Add date timepicker to [idYear] text box 
* @param idDay : id of text box day
* @param idMonth: id of text box month
* @param idYear: id of text box year
* @param changeMonth: 
* true: allow use select month from a combobox
* false: hide the month combobox 
* @param changeYear
* true: allow use select year from a combobox
* false: hide the year combobox  
* @param initCurrentDay
* true: will auto fill current date into day,month,year text box at start up
* false: day, month year text box is empty at start up
* @return
*/
function addDatePickerTime(idDay,idMonth,idYear,idTime,changeMonth,changeYear,initCurrentDay) {
	
	$(idTime).datepicker({
		dateFormat: 'dd/mm/yy',
		gotoCurrent: true,
		buttonImage: '../images/calendar.gif',
		buttonImageOnly: true,
		showOn: 'button',
		changeMonth: changeMonth,
		beforeShow: function (i, e) {            
            e.dpDiv.css('z-index', 10000);
    	}, 
		
		changeYear: changeYear,
		onSelect: function(dateText, inst) {  
			var dt=new Date();	
	        $(idDay).val(inst.selectedDay);
	
	        $(idMonth).val(inst.selectedMonth + 1);
	
	        $(idYear).val(inst.selectedYear);
	        var hour = dt.getHours()< 10? "0" + dt.getHours(): dt.getHours();
	        var min = dt.getMinutes()< 10? "0" + dt.getMinutes(): dt.getMinutes();
	        

			$(idTime).val(hour + ":" + min);
	
	    }
	});
	
	
	if (initCurrentDay == true) {
		var dt=new Date();
		var mo = dt.getMonth() + 1;  
		var day = dt.getDate(); 
		$(idDay).val(day < 10? "0" + day: day);
		$(idMonth).val(mo < 10? "0" + mo: mo);
		$(idYear).val(dt.getFullYear());
		var hour = dt.getHours()< 10? "0" + dt.getHours(): dt.getHours();
		var min = dt.getMinutes()< 10? "0" + dt.getMinutes(): dt.getMinutes();
		$(idTime).val(hour + ":" + min);
	}
	$(idTime).unbind();
    $(idTime).bind('keypress', function(event) {
    	var charCode = (event.which) ? event.which : event.keyCode;
    	//allow enter character [:] in time box
    	if (charCode == 58) {
    		return true;
    	}
    	return allowEnterIntegerNum(event,true);
    });
	
	
}
/**
 * Provide default prompt dialog with common needs
 * it will create dialog with default setting(model, and could be resized)
 * @param title : title of dialog
 * @param mess : message be displayed on dialog
 * @param callback : call back function for Positive button(Ok, Yes, Next, Select)
 * @param buttonType : the buttons for dialog:
 * YesNo : buttons Yes and No
 * OkCancel: buttons Ok and Cancel
 * SelectCancel: button Select and Cancel
 * NextCancel: button Next and Cancel
 * @param iconType: icon for message, the icon is displayed front the message
 * 'warn': warning icon
 * 'info': info icon
 * null: nothing
 * @param focusButton : the translate text of button be focused
 * ex: _('Yes') : the button have translate text of 'Yes' is focus
 * @return show dialog
 */

function promptConfirm(title,mess,callback,buttonType,iconType,focusButton) {	
	var b = jQuery(document.body);	
	var selector = "prompt-confirm-dialog";
	if (title == null) {
		title = '';
	}
	var msgbox = "<div id='" + selector + "' title='" + title + "'>" + mess + "</div>";
	if (iconType == 'warn') {		
		msgbox = "<div id='" + selector + "' title='" + title + "'><p><span class='ui-icon  ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>" + mess + "</p></div>";
	} else if (iconType == 'info') {
		msgbox = "<div id='" + selector + "' title='" + title + "'><p><span class='ui-icon ui-icon-info' style='float:left; margin:0 7px 20px 0;'></span>" + mess + "</p></div>";
	}
	$("#" + selector).remove();	
	b.append(msgbox);	
	var buttons = {};	
	if (buttonType == 'YesNo') {
		buttons[_('No')] = function() {
			$(this).dialog('close');
		};
		buttons[_('Yes')] = function () {
			if (callback(_('Yes'),b) == true) {
				$(this).dialog('close');
			}
		};				
	} else if (buttonType == 'OkCancel') {
		buttons[_('Cancel')] = function() {
			$(this).dialog('close');
		};
		buttons[_('Ok')] = function () {
			if (callback(_('Ok'),b) == true) {
				$(this).dialog('close');
			}
		};		
	} else if (buttonType == 'SelectCancel') {
		buttons[_('Cancel')] = function() {
			$(this).dialog('close');
		};
		buttons[_('Select')] = function () {
			if (callback(_('Select'),b) == true) {
				$(this).dialog('close');
			}
		};
		
	} else if (buttonType == 'NextCancel') {
		buttons[_('Cancel')] = function() {
			$(this).dialog('close');
		};
		buttons[_('Next')] = function () {
			if (callback(_('Next'),b) == true) {
				$(this).dialog('close');
			}
		};
		
	}
	
	$("#" + selector).dialog({
		autoOpen: true,			
		bgiframe: true,
		resizable: true,		
		modal: true,							
		buttons: buttons,
		dialogClass: 'custom-dialog'
	});	
	
	if (focusButton != null && focusButton != '') {	
		$("div[role='dialog'] div button").each(function (i) {
	        $(this).attr('class','ui-state-default ui-corner-all');
	      });
		$("div[role='dialog'] div button:contains('" + focusButton+ "')").attr('class',"ui-state-default ui-corner-all ui-state-focus")
		$("div[role='dialog'] div button:contains('" + focusButton+ "')").focus();
	}
}
/**
 * Provide a general dialog with flexible setting
 * @param selector : the id of html element be displayed in dialog
 * null: the dialog will generate it's own id(general-dialog) for the dialog
 * @param title: title of dialog
 * null: the title in selector element won't be override 
 * @param mess : message be displayed in dialog
 * null: the content of selector element won't be override
 * @param iconType: icon for message, the icon is displayed front the message
 * 'warn': warning icon
 * 'info': info icon
 * 'ok'	 : Check icon 
 * 'error' : Punctuation icon	
 * null: nothing
 * @param options : options for dialog
 * null: it will create dialog with default setting(the box with no button, model, and could be resized)
 * @param focusButton : the translate text of button be focused
 * ex: _('Yes') : the button have translate text of 'Yes' is focus
 * @return show dialog
 * @return
 */
function generalDialog(selector,title,mess,iconType,options,focusButton) {
	var b = jQuery(document.body);	
	var msgbox = '';
	var icon = '';
	
	if (selector == null || $.trim(selector) == '' || $('#' + selector).html() == null) {
		
		selector = "general-dialog";		
		$("#general-dialog").remove();
		msgbox = "<div id='general-dialog' title=''></div>";		
		b.append(msgbox);		
	}	
	
	if (iconType == 'warn') {		
		icon = "<span class='ui-icon  ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>";
	} else if (iconType == 'info') {
		icon = "<span class='ui-icon ui-icon-info' style='float:left; margin:0 7px 20px 0;'></span>";
	} else if (iconType == 'ok') {
		icon = "<span class='ui-icon ui-icon-check' style='float:left; margin:0 7px 20px 0;'></span>";		
	} else if(iconType == 'error') {
		icon = "<span class='ui-icon ui-icon-notice' style='float:left; margin:0 7px 20px 0;'></span>";				
	}
	
	
	if (options == null || options =='') {			
		options = {
				autoOpen: true,			
				bgiframe: true,
				resizable: true,		
				modal: true,
				buttons: {}
		}
	}
	
	options['dialogClass'] = 'custom-dialog';
	
	var len = $('body').find('#' + selector).length;	
	if ($('div[role="dialog"] div[id="' + selector + '"]').html() != null && len == 1) {
		$('#' + selector).dialog( 'destroy' );
		if (title != null) {
			$('#' + selector).attr('title',title);
		}
		if (mess != null) {
			$('#' + selector).html("<p>" + icon + mess) + "</p>";
		}
		$('#' + selector).dialog(options);		
	} else if ($('div[role="dialog"] div[id="' + selector + '"]').html() != null && len > 1) {		
		$('div[role="dialog"] div[id="' + selector + '"]').remove();
		if (title != null) {
			$('#' + selector).attr('title',title);
		}
		if (mess != null) {
			$('#' + selector).html("<p>" + icon + mess) + "</p>";
		}
		$('#' + selector).dialog(options);
	} else {		
		if (title != null) {
			$('#' + selector).attr('title',title);
		}
		if (mess != null) {
			$('#' + selector).html("<p>" + icon + mess) + "</p>";
		}
		$('#' + selector).dialog(options);
	}

	if (focusButton != null && focusButton != '') {
		
		$("div[role='dialog'] div button").each(function (i) {
	        $(this).attr('class','ui-state-default ui-corner-all');
	      });
		$("div[role='dialog'] div button:contains('" + focusButton+ "')").attr('class',"ui-state-default ui-corner-all ui-state-focus");
		$("div[role='dialog'] div button:contains('" + focusButton+ "')").focus();
	}
	return $('#' + selector);

}
/**
 * Constructor for a custom locale object
 * @param decimalPoint: String containing the symbol used as the decimal delimiter. 
 * @param thousandSep: String containing the symbol used as a separator for groups of digits to the left of the decimal delimiter. 
 * @param fracDigits: Number representing the number of fractional digits to be written to the right of the decimal delimiter
 * @return: object with properties: decimalPoint, thousandSep, fracDigits
 */
function locale(decimalPoint, thousandSep, fracDigits) {
	  var lc = {decimalPoint:'', thousandSep: '', fracDigits: ''};
	  lc.decimalPoint = new String(decimalPoint);
	  lc.thousandSep = new String(thousandSep);
	  lc.fracDigits = fracDigits;
	  return lc;
}

/**
 * Returns number num rounded to the fracDigits'th decimal
 * @param num
 * @param fracDigits: Number representing the number of
 * fractional digits to be written to the right of the decimal delimiter
 * @return: rounded Fload number
 * Ex: 1.527 -> if fracDigits = 2 -> result: 1.53
 */
function roundFloat(num, fracDigits) {
	  var factor = Math.pow(10, fracDigits);
	  return(Math.round(num*factor)/factor);
}     
/**
 * 
 * @param num
 * @param lc
 * @return
 * Returns a string representing 
 * num formatted with lc.decimalPoint as decimal separator
 */
function toLcString(num, lc) {
	  var str = new String(num);
	  var aParts = str.split(".");	  
	  if (aParts[0] != null) {
		  var len = aParts[0].length;
		  var text = '';
		  var count = 0;
		  for ( var int = (len-1); int >=0; int--) {
			  text += aParts[0][int];
			  count ++;
			  if (count == 3 && int >0) {
				  count =0;
				  text += lc.thousandSep;
			  }
		  }
		  var result ='';
		  for ( var int = (text.length - 1); int >=0; int--) {
			  result += text[int];			  
		  }
		  aParts[0] = result;
	  }
	  return(aParts.join(lc.decimalPoint));
 }
/**
 * 
 * @param num
 * @param lc: local object
 * @return
 * Returns a string representing 
 * num formatted with lc.decimalPoint as decimal separator
 */
function formatNum(num, lc) {
	var sNum = new String(roundFloat(num, lc.fracDigits));
	  if(lc.fracDigits>0) {
	    if(sNum.indexOf(".")<0)
	      sNum = sNum+".";
	    while(sNum.length < 1+sNum.indexOf(".")+lc.fracDigits)
	      sNum = sNum+"0";
		  }
  return(toLcString(sNum, lc));
}
/**
 * Returns the numerical value of the number contained in 
 * str and formatted according to 
 * lc.thousandSep and 
 * lc.decimalPoint properties
 * @param str: String
 * @param lc: locale Object
 * @return
 */
function parseLcNum(str, lc) {
	  var sNum = new String(str);
	  var aParts = sNum.split(lc.thousandSep);
	  sNum = aParts.join("");
	  aParts = sNum.split(lc.decimalPoint);
	  return(parseFloat(aParts.join(".")));
}

/**
* Show/hide loader when an AJAX action are executing. If loader is show then action button is hide and vice versa
* @param idLoader id of the loader to be show/hide
* @param idActionButton id of the button to be show/hide
* @param show param to set status of the loader. If show=true then show the loader else hide the element
*/
function showAjaxLoader(idLoader, idActionButton, show){
	if (show){
	    $('#' + idLoader).show();
	    $('#' + idActionButton).hide();
	}
	else {
	    $('#' + idLoader).hide();
	    $('#' + idActionButton).show();
	}
}

function toggleModalAjaxLoader() {
	$('.modalOverlay').toggle();
}

 //set select for select box.
 function setSelectedItem(selectBoxId, selectedOptionValue){
	 var first = true;	 
	 $("select#" + selectBoxId + " option").each(function () {
		 if (selectedOptionValue == 0 && first == true) {
			 first = false;		
			 $(this).attr('selected', 'selected');
		 } else if ($(this).val() == selectedOptionValue) {
			 $(this).attr('selected', 'selected');
		 } else {
			 $(this).attr('selected', '');
		 }
	 });
 }
   
 
 function displayError(errorMess) {
	 var buttons = {};
		buttons[_('Close')] = function() {
			$(this).dialog('close');
		};
		
		generalDialog(null, _('Error'), errorMess, 'error', {
			autoOpen: true,			
			bgiframe: true,
			resizable: false,
			modal: true,
			buttons: buttons,
			dialogClass: 'custom-dialog'
		}, _('Close'));
	}
 
 function showMessage(targetId, message, status) {		 	
		if (status == 'success') {
			$('#' + targetId).css('color', 'green').text(message);			
		} else if (status == 'error') {
			$('#' + targetId).css('color', 'red').text(message);		
		}

 }
 function countItemInListBox(listBoxId){
	 var count = 0;
	 $('#' + listBoxId + ' :option').each(function() {
		 count ++;		 
	 });
	 return count;	    
 }
 
 function clearText(targetId){
    $('#' + targetId).text('');
    $('#' + targetId).val('');
}
 
function pad(str,n,ch) {
	  if(typeof str=='number') {
	    str=String(str);
	    if(arguments.length<3) ch='0';
	  }
	  var N=Math.abs(n);
	  if(str.length>=N) {
	    return n>=0 ? str.substr(0, n) : str.substr(str.length-N);
	  }
	  return (n>=0 ? str : '') + new Array(N-str.length+1).join((ch||' ').charAt(0)) + (n<0 ? str : '');
}
 
function moveNext(event, nextId) {
		if (event==null || event.which == 13){
			$('#' + nextId).focus();
			$('#' + nextId).select();
		}
		if (event != null) {
			 event.stopPropagation();
		 }
		
}
function moveNextWithCurId(event, curId, triggerEvent) {
	 if (event == null || event.which == 13){
		 
		 if (triggerEvent != null) {
	    	 $('#' + curId).trigger(triggerEvent); 
	     }
		 var fields = $('#' + curId).parents('form:eq(0),body').find('button,input,textarea,select').not('[type=hidden]');
		 var index = fields.index( $('#' + curId) );
	        if ( index > -1 && ( index + 1 ) < fields.length ) {
	            fields.eq( index + 1 ).focus();
	            fields.eq( index + 1 ).select();
	        }	
	     

	 }
	 if (event != null) {
		 event.stopPropagation();
	 }
	return false;
}

function moveNextBlur(event, currId, nextId) {
		if (event.which == 13){
			$('#' + currId).trigger('blur');
			$('#' + nextId).focus();
			$('#' + nextId).select();
		}
		
}

function setElementData(elementId, data) {
    if ($('#' + elementId).length > 0) {
        var obj =   $('#' + elementId);
        var tagName =   obj.get(0).tagName.toLowerCase();
        switch (tagName) {
            case 'textarea':
                obj.val(data);
                break;
            case 'span':
            case 'label':
                obj.text(data);
                break;
            case 'input':
            	var type	=	obj.get(0).type.toLowerCase();
            	if (type == 'text') {
            		obj.val(data);                    
            	}
            	else if(type == 'checkbox' || type == 'radio') {
            		if (parseInt(data)) {
            			obj.attr('checked', 'checked');
            		}
            		else {
            			obj.removeAttr('checked');
            		}
            	}
            	break;
            default:
                obj.html(data);
                break;
        }
    }
}

function resetFormExt(containerId, resetHidden, clearSpan) {
    $('#' + containerId).clearForm();
    if (resetHidden == true) {
        $('#' + containerId + ' input[type=hidden]').each(function() {
            $(this).val('');
        });    
    }
    if (clearSpan!= null && clearSpan == true) {
        $('#' + containerId + ' span').each(function() {
            $(this).text('');
        });
    }
    $('#' + containerId + ' select').each(function() {
        $(this).html('');
    });
}

function toNormalBorder(id) {
     $('#' + id).css("border-color", "#AAA");
}

function resetInputBorders(containerId) {
    $('#' + containerId + ' input, select, textarea').not('[type=hidden]').each(function() {
        $(this).css('border-color', '#AAA');
    });
}

function parseVND(str) {
	var a = parseInt(str, 10);
	
	if (isNaN(a) || a == 0) return '0';
	
	var objStr = String(a);										
	if (objStr.length <= 3) {
		text = objStr + thousandSep + '000';
	} else {
		var arr = new Array();
		while (objStr.length > 3) {				
			var temp = objStr.substring(objStr.length - 3);
			arr.push(temp);
			objStr = objStr.substring(0, objStr.length - 3);					
		}
		arr.push(objStr);
		arr.reverse();
		text = arr.join(thousandSep) + thousandSep +'000';
	}
	return text + ' VNĐ';
}

function in_array (needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false

    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}